package com.qishanor.framework.web.filter;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @description: 参数请求包装器
 * @author: 周振林
 * @date: 2022-04-25
 * @Copyright: 博客：http://www.zhouzhenlin.com - 沉淀、分享、成长、让自己和他人都有所收获
 **/


public class ParameterRequestWrapper extends HttpServletRequestWrapper {

    private Map<String , String[]> params = new HashMap<>();

    public ParameterRequestWrapper(HttpServletRequest request) {
        super(request);
        Map<String, String[]> requestMap=request.getParameterMap();
        this.params.putAll(requestMap);
        this.modifyParameterValues();
    }

    public void modifyParameterValues(){
        Set<String> set = params.keySet();
        Iterator<String> it = set.iterator();
        while(it.hasNext()){
            String key= it.next();
            String[] values = params.get(key);
            for (int i = 0; i < values.length; i++) {
                if(ObjectUtil.isNotNull(values[i])){
                    values[i] = values[i].trim();
                }
            }
            params.put(key, values);
        }
    }

    @Override
    public String getParameter(String name) {
        String[]values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        Console.log(super.getHeader(HttpHeaders.CONTENT_TYPE));
        if(!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)){
            return super.getInputStream();
        }
        String json = IoUtil.readUtf8(super.getInputStream());
        if (StrUtil.isEmpty(json)) {
            return super.getInputStream();
        }

        Map<String,Object> map= jsonStringToMap(json);
        ByteArrayInputStream bis = new ByteArrayInputStream(JSONUtil.toJsonStr(map).getBytes("utf-8"));
        return new MyServletInputStream(bis);
    }

    public static Map<String, Object> jsonStringToMap(String jsonString) {
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);
        for (Object k : jsonObject.keySet()) {
            Object o = jsonObject.get(k);
            if (o instanceof JSONArray) {
                List<Object> list = new ArrayList<>();
                Iterator<Object> it = ((JSONArray) o).iterator();
                while (it.hasNext()) {
                    Object obj = it.next();
                    if (obj instanceof JSONObject){
                        list.add(jsonStringToMap(obj.toString()));
                    }
                    if (obj instanceof String) {
                        list.add(obj.toString().trim());
                    } else {
                        list.add(obj);
                    }
                }
                map.put(k.toString(), list);
            } else if (o instanceof JSONObject) {
                map.put(k.toString(), jsonStringToMap(o.toString()));
            } else {
                if (o instanceof String) {
                    map.put(k.toString(), o.toString().trim());
                } else {
                    map.put(k.toString(), o);
                }
            }
        }
        return map;
    }

    class MyServletInputStream extends ServletInputStream {
        private ByteArrayInputStream bis;
        public MyServletInputStream(ByteArrayInputStream bis){
            this.bis=bis;
        }
        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener listener) {

        }
        @Override
        public int read(){
            return bis.read();
        }
    }
}



